//
//  BaseLocationManagerVC.m
//  customer
//
//  Created by Holothurian on 2018/10/29.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "BaseLocationManagerVC.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <MAMapKit/MAMapView.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <MAMapKit/MAPointAnnotation.h>
#import "BaseLocationTableCell.h"
#import <MAMapKit/MAMapKit.h>
//#import <AMap2DMap/MAMapKit/MAPinAnnotationView.h>

static NSString *CellIDentifier = @"CellIDentifier";
static NSString *TopCellIDentifier = @"TopCellIDentifier";
@interface BaseLocationManagerVC ()<UITableViewDelegate,UITableViewDataSource,AMapLocationManagerDelegate,MAMapViewDelegate,AMapSearchDelegate,UISearchBarDelegate>{
    NSIndexPath *_currentIndexPath;
    BOOL _isActive;
    BOOL _isBack;
}

@property (nonatomic,strong)UISearchBar *searchBar;

/**
 定位管理类
 */
@property (nonatomic,strong)AMapLocationManager *locationManager;

/**
POI关键字搜索
 */
@property (nonatomic,strong)AMapPOIKeywordsSearchRequest *poiSearchRequest;

/**
 地图
 */
@property (nonatomic,strong)MAMapView *mapView;

/**
 搜索工具类
 */
@property (nonatomic,strong)AMapSearchAPI *searchAPI;

/**
 大头针
 */
@property (nonatomic,strong)MAPointAnnotation *pointAnnotation;

/**
 记录经纬度
 */
@property (nonatomic,strong)CLLocation *location;

/**
 记录当前经纬度
 */
@property (nonatomic,strong)CLLocation *currentLocation;

/**
 逆地理编码
 */
@property (nonatomic,strong)AMapLocationReGeocode *currentRegeocode;

/**
 位置信息Model
 */
@property (nonatomic,strong)DecorateLocationModel *locationModel;

/**
 tableView数据源
 */
@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)UITableView *tableView;

/**
 poi搜索分页
 */
@property (nonatomic,assign)NSInteger page;

@end

@implementation BaseLocationManagerVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createMapView];
    [self initWithSearchApi];
    [self createRightBarButton];
    [self createSearchController];
    [self createTableView];
    
   
}

- (void)createRightBarButton{
    UIBarButtonItem *rightBar =  [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStyleDone target:self action:@selector(rightBarAction)];
    rightBar.tintColor = [UIColor blackColor];
    self.navigationItem.rightBarButtonItem = rightBar;
    
}

- (void)createSearchController{
    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, F_DEVICE_W, 50)];
    self.searchBar.placeholder = @"小区/写字楼/学校等";
    self.searchBar.tintColor = [UIColor appColor];
    self.searchBar.delegate = self;
    [self.searchBar setReturnKeyType:UIReturnKeySearch];
    [self.view addSubview:self.searchBar];
}

#pragma mark - - 选择完地址进行回调
- (void)rightBarAction{
    if (_currentIndexPath.row < [self.dataArray count]) {
        AMapPOI *poi = self.dataArray[_currentIndexPath.row];
        self.locationModel.longitude = [NSString stringWithFormat:@"%lf",poi.location.longitude];
        self.locationModel.latitude = [NSString stringWithFormat:@"%lf",poi.location.latitude];
        self.locationModel.province = poi.province;
        self.locationModel.city = poi.city;
        self.locationModel.country = poi.district;
        self.locationModel.citycode = poi.postcode;
        self.locationModel.number = @"";
        self.locationModel.detail = [NSString stringWithFormat:@"%@",poi.address];
        self.locationModel.prefixArea = [NSString stringWithFormat:@"%@%@",poi.province,poi.city];
        self.locationModel.suffixArea = [NSString stringWithFormat:@"%@%@",poi.district,poi.address];
        if (self.locationBlock) {
            self.locationBlock(self.locationModel);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self configLocationManager];

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.locationManager stopUpdatingLocation];
    self.locationManager = nil;
    self.mapView = nil;
    self.searchAPI = nil;
    self.poiSearchRequest = nil;
    self.currentRegeocode = nil;
}

- (void)createMapView{
    self.title = @"地址选择";
    
    _mapView = [[MAMapView alloc]initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, F_DEVICE_W, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - 250)];
    _mapView.delegate = self;
    //打开用户位置
    _mapView.showsUserLocation = YES;
    
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    //设定定位精度。默认为kCLLocationAccuracyBest
    _mapView.desiredAccuracy = kCLLocationAccuracyBest;
    /// 设定定位的最小更新距离。默认为kCLDistanceFilterNone，会提示任何移动
    _mapView.distanceFilter = 15.f;
    //隐藏指南针
    _mapView.showsCompass = NO;
    //隐藏比例尺
    _mapView.showsScale = YES;
    
    //手势控制
    _mapView.zoomEnabled = YES;
    //是否支持平移
    _mapView.scrollEnabled = YES;
    //设置地图语言
    _mapView.language = MAMapLanguageZhCN;
    /// 缩放级别, [3, 20]
    _mapView.zoomLevel = 15;
    [self.view addSubview:_mapView];
    
    self.locationModel = [[DecorateLocationModel alloc]init];
    _isBack = YES;
}

- (void)createTableView{
    
    UIButton *locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    locationBtn.frame = CGRectMake(F_DEVICE_W - 50, F_DEVICE_H - 300, 40, 40);
    [locationBtn setImage:[UIImage imageNamed:@"locationSet"] forState:UIControlStateNormal];
    [locationBtn setImage:[UIImage imageNamed:@"locationSet"] forState:UIControlStateSelected];
    [locationBtn addTarget:self action:@selector(locationAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:locationBtn];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, F_DEVICE_H - 250, F_DEVICE_W, 250) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    _currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self searchAroundLocation];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.page++;
        [self searchAroundLocation];
    }];
    
}

- (void)locationAction{
    _isBack = YES;
    //开始定位
    [self.locationManager startUpdatingLocation];
    //设置允许连续定位逆地理位置
    [self.locationManager  setLocatingWithReGeocode:YES];
    self.location = self.currentLocation;
    _currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView reloadData];
}

- (void)endRefresh{
    if (self.page == 1) {
        [self.tableView.mj_header endRefreshing];
    }else{
        [self.tableView.mj_footer endRefreshing];
    }
}

//
//基础定位
- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];

    [self.locationManager setDelegate:self];
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [self.locationManager setLocationTimeout:1];
    [self.locationManager setReGeocodeTimeout:1];

    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    [self.locationManager setAllowsBackgroundLocationUpdates:NO];
    //设置允许连续定位逆地理位置
    [self.locationManager  setLocatingWithReGeocode:YES];
    //开始定位
    [self.locationManager startUpdatingLocation];
    self.page = 1;
    
}
- (void)initWithSearchApi{
    self.pointAnnotation = [[MAPointAnnotation alloc] init];
    self.pointAnnotation.lockedToScreen = YES;
    self.pointAnnotation.lockedScreenPoint = CGPointMake(F_DEVICE_W/2.0, self.mapView.viewHeight/2.0);
    [self.mapView addAnnotation:self.pointAnnotation];
    
    self.searchAPI = [[AMapSearchAPI alloc]init];
    self.searchAPI.delegate = self;
    //构造AMapPOIAroundSearchrRequest对象，设置周边请求参数
    self.poiSearchRequest = [[AMapPOIKeywordsSearchRequest alloc]init];
    self.poiSearchRequest.types = @"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施";
    self.poiSearchRequest.sortrule = 0;
    self.poiSearchRequest.page = self.page;
    self.poiSearchRequest.requireExtension = YES;
}


- (void)searchAroundLocation{
    
    CLLocationCoordinate2D coordinate = [self.mapView convertPoint:CGPointMake(F_DEVICE_W/2.0, self.mapView.viewHeight/2.0) toCoordinateFromView:self.mapView];
    CLLocation *cllocation = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    self.location = cllocation;
    self.poiSearchRequest.location = [AMapGeoPoint locationWithLatitude:self.location.coordinate.latitude longitude:self.location.coordinate.longitude];
    [self.searchAPI AMapPOIKeywordsSearch:self.poiSearchRequest];

    [UIView animateWithDuration:0.1 animations:^{
        [self.mapView setCenterCoordinate:self.location.coordinate animated:YES];
        [self.mapView addAnnotation:self.pointAnnotation];
    }];
}

#pragma mark - 大头针方法
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (!annotationView)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.pinColor = MAPinAnnotationColorRed;
        return annotationView;
    }
    return nil;
}
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    self.page = 1;
    [self searchAroundLocation];
}

/**
 * @brief 逆地理编码查询回调函数
 * @param request  发起的请求，具体字段参考 AMapReGeocodeSearchRequest 。
 * @param response 响应结果，具体字段参考 AMapReGeocodeSearchResponse 。
 */
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response{
    NSLog(@"response......%@",response);
}


- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error{
    NSLog(@"error......%@",error);
}

#pragma - mark - AMapLocationManagerDelegate
#pragma mark - 位置更新方法需要走的方法
/**
 *  @brief 连续定位回调函数.注意：如果实现了本方法，则定位信息不会通过amapLocationManager:didUpdateLocation:方法回调。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param location 定位结果。
 *  @param reGeocode 逆地理信息。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode{
  
    NSLog(@"location:%@ \nreGeocode:%@\n",location,reGeocode);
    if (reGeocode) {
        if ((self.location.coordinate.latitude != self.currentLocation.coordinate.latitude) || _isBack == YES) {
            self.currentLocation = location;
            self.page = 1;
            if (_isBack) {
                _isBack = NO;
                self.poiSearchRequest.location = [AMapGeoPoint locationWithLatitude:self.currentLocation.coordinate.latitude longitude:self.currentLocation.coordinate.longitude];
                [self.searchAPI AMapPOIKeywordsSearch:self.poiSearchRequest];
                [self.mapView setCenterCoordinate:self.currentLocation.coordinate animated:YES];
                [self.mapView addAnnotation:self.pointAnnotation];
            }else{
                [self searchAroundLocation];
            }
        }
    }
}

#pragma mark - 搜索周边
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    if (response.pois.count == 0) {
        return;
    }
    if (self.page == 1) {
        self.dataArray = [NSMutableArray arrayWithArray:response.pois];
    }else{
        [self.dataArray addObjectsFromArray:response.pois];
    }
    [self.tableView reloadData];
    [self endRefresh];
}

/**
 *  @brief 定位权限状态改变时回调函数
 *  @param manager 定位 AMapLocationManager 类。
 *  @param status 定位权限状态。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    NSLog(@"%@",manager);
}

/**
 *  @brief 当定位发生错误时，会调用代理的此方法。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param error 返回的错误，参考 CLError 。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error{
    [self showErrorTipWithTitle:@"定位错误"];
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.dataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BaseLocationTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIDentifier];
    if (!cell) {
        cell = [[BaseLocationTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIDentifier];
    }
    if (indexPath == _currentIndexPath) {
        cell.selectImgView.hidden = NO;
    }else{
        cell.selectImgView.hidden = YES;
    }
    AMapPOI *poi = self.dataArray[indexPath.row];
    cell.nameLabel.text = [NSString stringWithFormat:@"%@",poi.name];
    cell.subTitleLabel.text = [NSString stringWithFormat:@"%@%@%@",poi.city,poi.district,poi.address];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _currentIndexPath = indexPath;
    if (_isActive == YES) {
        _isActive = NO;
        AMapPOI *poi = self.dataArray[indexPath.row];
        CLLocation *cllocation = [[CLLocation alloc]initWithLatitude:poi.location.latitude longitude:poi.location.longitude];
        [self.mapView setCenterCoordinate:cllocation.coordinate];
        [self.mapView addAnnotation:self.pointAnnotation];
        self.tableView.frame = CGRectMake(0, F_DEVICE_H - bottomPadding(250), F_DEVICE_W, bottomPadding(250));
    }
    AMapPOI *poi = self.dataArray[indexPath.row];
    self.locationModel.province = poi.province;
    self.locationModel.city = poi.city;
    self.locationModel.country = poi.district;
    self.locationModel.citycode = poi.postcode;
    self.locationModel.number = @"";
    self.locationModel.detail = [NSString stringWithFormat:@"%@",poi.address];
    self.locationModel.prefixArea = [NSString stringWithFormat:@"%@%@",poi.province,poi.city];
    self.locationModel.suffixArea = [NSString stringWithFormat:@"%@%@",poi.district,poi.address];
    [self.tableView reloadData];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.f;
}


#pragma mark - UISearchBarDelegate
//点击了取消按钮
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    _isActive = NO;
    self.searchBar.text = @"";
    [self.searchBar resignFirstResponder];
    [self.searchBar setShowsCancelButton:NO animated:YES];
    self.tableView.frame = CGRectMake(0, F_DEVICE_H - 250, F_DEVICE_W, 250);
}

//点击了搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    _isActive = YES;
    self.page = 1;
    [self.searchBar resignFirstResponder];
    [self.searchBar setShowsCancelButton:NO animated:YES];
    self.poiSearchRequest.keywords = searchBar.text;
    [self searchAroundLocation];
     self.tableView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT + 50, F_DEVICE_W , F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(50));
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [self.searchBar setShowsCancelButton:YES animated:YES];
    for (id obj in [searchBar subviews]) {
        if ([obj isKindOfClass:[UIView class]]) {
            for (id obj2 in [obj subviews]) {
                if ([obj2 isKindOfClass:[UIButton class]]) {
                    UIButton *btn = (UIButton *)obj2;
                    [btn setTitle:@"取消" forState:UIControlStateNormal];
                    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                }
            }
        }
    }
    _isActive = YES;
    self.page = 1;
    self.poiSearchRequest.keywords = searchBar.text;
    [self searchAroundLocation];
    self.tableView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT + 50, F_DEVICE_W , F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(50));
    return YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    for (id obj in [searchBar subviews]) {
        if ([obj isKindOfClass:[UIView class]]) {
            for (id obj2 in [obj subviews]) {
                if ([obj2 isKindOfClass:[UIButton class]]) {
                    UIButton *btn = (UIButton *)obj2;
                    [btn setTitle:@"取消" forState:UIControlStateNormal];
                    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                }
            }
        }
    }
    _isActive = YES;
    self.page = 1;
    self.poiSearchRequest.keywords = searchBar.text;
    [self searchAroundLocation];
    self.tableView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT + 50, F_DEVICE_W , F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(50));
}

- (AMapSearchAPI *)searchAPI{
    if (!_searchAPI) {
        _searchAPI = [[AMapSearchAPI alloc]init];
        _searchAPI.delegate = self;
    }
    return _searchAPI;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
